<template>
  <div>
    <DynamicTable
      ref="dynamicTableRef"
      row-key="id"
      :header-title="$t('routes.system.system.role.list')"
      :data-request="loadData"
      :columns="columns"
      bordered
      size="small"
      :showIndex="false"
      :fetch-config="{ listField: 'data', totalField: 'count' }"
    >
      <template #toolbar>
        <a-button v-if="canAdd" type="primary" @click="add">
          {{ $t('common.add') }}
        </a-button>
      </template>
    </DynamicTable>
  </div>
</template>
<script lang="tsx" setup>
  import { ref } from 'vue'
  import { message } from 'ant-design-vue'
  import { DynamicTable } from '@/components/core/dynamic-table'
  import { useFormModal } from '@/hooks/useModal/useFormModal'
  import type { FormSchema } from '@/components/core/schema-form/src/types/form'
  import type { TableColumn } from '@/components/core/dynamic-table'
  import { useI18n } from '@/hooks/useI18n'
  import { ApiDescription, HttpMethod } from '@/utils/apiDescription'
  import canAccessView from '@/utils/accessCheck'
  import {
    getAllRole,
    addRole,
    deleteRole,
    getAgencyConf,
    getAllService,
    getAllApi,
    verifyApis,
  } from '@/api/middleSystem'
  import { WarnLevelEnum } from '@/model/enums'
  import { useRouter } from 'vue-router'
  import { formatTreeApi } from '@/utils/filters'
  import { funcA } from './detail.vue'

  funcA()

  defineOptions({
    name: 'Role',
  })

  const canAdd = ref(canAccessView(new ApiDescription('/role', HttpMethod.Post)))
  const canUpdate = ref(canAccessView(new ApiDescription('/role/{roleId}', HttpMethod.Put)))
  const canDelete = ref(canAccessView(new ApiDescription('/role/{roleId}', HttpMethod.Delete)))

  const { t } = useI18n()
  const dynamicTableRef = ref<InstanceType<typeof DynamicTable>>()

  /**
   * 表格列
   */
  const columns: TableColumn<any>[] = [
    {
      title: '角色名',
      dataIndex: 'name',
    },
    {
      title: '开放注册',
      dataIndex: 'allowRegister',
      hideInSearch: true,
      customRender: ({ record }) => {
        return record.allowRegister ? '是' : '否'
      },
    },
    {
      title: '用户数量（人）',
      dataIndex: 'userCount',
      hideInSearch: true,
    },
    {
      title: '标识符',
      dataIndex: 'tag',
      hideInSearch: true,
    },
    {
      title: '权限级别',
      dataIndex: 'level',
      hideInSearch: true,
    },
    {
      title: '敏感级别',
      dataIndex: 'warnLevel',
      hideInSearch: true,
      customRender: ({ record }) => {
        let style = ''
        if (record.warnLevel == 1) style = 'color: #E6A23C'
        if (record.warnLevel == 2) style = 'color: #F56C6C'
        return <span style={style}>{WarnLevelEnum[record.warnLevel]}</span>
      },
    },
    {
      title: '操作',
      dataIndex: 'ACTION',
      hideInSearch: true,
      actions: ({ record }) => [
        {
          label: '查看',
          hide: !canUpdate.value,
          onClick: () => detail(record),
        },
        {
          label: t('common.delete'),
          danger: true,
          hide: !canDelete.value,
          popConfirm: {
            title: t('column.confirmDel'),
            onConfirm: () => del(record),
          },
        },
      ],
    },
  ]

  /**
   * 加载数据
   */
  const loadData = async params => {
    const { name, pageIndex, pageSize } = params
    const data = await getAllRole(name, pageIndex, pageSize)
    return data
  }

  const router = useRouter()
  /**
   * 查看
   */
  const detail = record => {
    router.push(`/system/role/detail/${record.id}`)
  }

  /**
   * 删除
   */
  const del = async record => {
    await deleteRole(record.id)
    message.success('操作成功')
    dynamicTableRef.value?.reload()
  }

  // todo
  let updateformRef: any
  const changeNum = value => {
    console.log(value)
  }

  const [showModal] = useFormModal()

  const formSchemas: FormSchema[] = [
    {
      field: 'name',
      component: 'Input',
      label: '角色名称',
      rules: [{ required: true }],
    },
    {
      field: 'tag',
      component: 'Input',
      label: '标识符',
      rules: [{ required: true }],
    },
    {
      field: 'level',
      component: 'Input',
      label: '权限级别',
      rules: [{ required: true }],
    },
    {
      field: 'num',
      component: 'InputNumber',
      label: '服务角色',
      componentProps: {
        min: 0,
        onChange: changeNum,
      },
      rules: [{ required: true }],
      defaultValue: 0,
    },
    // {
    //   field: 'name',
    //   component: 'Input',
    //   label: '支持用户管理的服务',
    //   rules: [{ required: true }],
    // },
    // {
    //   field: 'name',
    //   component: 'Input',
    //   label: '服务角色标识',
    //   rules: [{ required: true }],
    // },
    {
      field: 'allowRegister',
      component: 'Switch',
      label: '开放注册',
      defaultValue: false,
    },
    {
      field: 'isAdminRole',
      component: 'Switch',
      label: '访问后台视图',
      defaultValue: false,
    },
    {
      field: 'allowUseAgency',
      component: 'Switch',
      label: '允许使用代理',
      defaultValue: false,
    },
    {
      field: 'agencyConfIds',
      component: 'Select',
      label: '允许代理服务',
      vIf: ({ formModel }) => formModel['allowUseAgency'] == true,
      componentProps: {
        mode: 'multiple',
        showSearch: true,
        optionFilterProp: 'label',
        request: async () => {
          return (await getAgencyConf.request({ pageSize: 100000 })).data.map((item: any) => {
            return { label: item.name, value: item.id }
          })
        },
      },
    },
    {
      field: 'apis',
      component: 'Tree',
      label: '权限分配',
      componentProps: {
        defaultExpandAll: true,
        checkable: true,
        multiple: true,
        vModelKey: 'checkedKeys',
        fieldNames: { children: 'children', title: 'name', key: 'id' },
      },
    },
  ]

  function extractItemsByIds(tree, ids) {
    let result: any = []
    function traverse(node) {
      if (ids.includes(node.id) && !node.children) {
        result.push(node)
      }
      if (node.children && node.children.length > 0) {
        node.children.forEach(child => traverse(child))
      }
    }
    tree.forEach(rootNode => traverse(rootNode))
    return result
  }

  // 支持用户管理的服务(新增)
  const currentService = ref<any>([])
  const supportUserInfoManageService = ref<any>([])
  // 服务角色标识(新增)
  const roleTags = ref<any>([])
  const roleOptions = ref<any>([])

  // 权限控制组件数据源
  const apiTree = ref<any>([])

  const add = async () => {
    supportUserInfoManageService.value = []
    roleOptions.value = []
    let services: any = (await getAllService(1, 100000, '', true)).data
    services.forEach(service => {
      supportUserInfoManageService.value.push({
        value: service.appId,
      })
      const userRoleTags = Object.keys(service.userRoleTags)
      const tempTags: any[] = []
      userRoleTags.forEach(tag => {
        tempTags.push({
          value: tag,
        })
      })
      roleOptions.value.push(tempTags)
    })

    const { data: apiData } = await getAllApi()
    const temporaryTree = formatTreeApi(apiData)
    const { data: serviceData } = await getAllService(1, 100000, '')
    serviceData.push({ appId: 'middleSystem', name: '中台服务', children: [] })
    serviceData.forEach((item: any) => {
      item.id = item.appId ? item.appId : 'middleSystem'
      item.children = []
      temporaryTree.forEach((value: any) => {
        if (item.appId == value.children[0].appId) item.children.push(value)
        if (!value.children[0].appId && item.id == 'middleSystem') item.children.push(value)
      })
    })
    apiTree.value = serviceData

    const [formRef] = await showModal({
      modalProps: {
        title: t('common.add'),
        width: '40%',
        onFinish: async values => {
          let {
            name,
            tag,
            level,
            allowRegister,
            isAdminRole,
            allowUseAgency,
            agencyConfIds,
            apis,
            password,
          } = values
          let filteredItems = apis?.length ? extractItemsByIds(apiTree.value, apis) : []
          let rts: any[] = []
          roleTags.value.forEach((rt, index) => {
            rts.push({
              service: currentService.value[index],
              tag: rt,
            })
          })

          let flag = await verifyApis(filteredItems)

          if (flag && !password) {
            message.warning('您已勾选了敏感权限接口,需要重新输入密码对操作进行确认!')
            formRef?.appendSchemaByField({
              field: 'password',
              component: 'Input',
              label: '密码',
              rules: [{ required: true }],
            })
            throw new Error('您已勾选了敏感权限接口,需要对操作进行确认!')
          }

          await addRole(
            name,
            filteredItems,
            allowRegister,
            isAdminRole,
            allowUseAgency,
            allowUseAgency ? agencyConfIds : [],
            tag,
            +level,
            rts,
            password,
          )
          message.success('操作成功')
          dynamicTableRef.value?.reload()
        },
      },
      formProps: {
        labelWidth: 100,
        layout: 'horizontal',
        schemas: formSchemas,
      },
    })
    updateformRef = formRef
    formRef?.updateSchema([
      {
        field: 'apis',
        componentProps: { treeData: apiTree.value },
      },
    ])
  }
</script>
<script lang="tsx">
  export var funcB = () => {
    console.log('----------------------------b')
  }
</script>
